package com.markerhub.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.markerhub.entity.HealthKnowledge;
import com.markerhub.entity.HealthKnowledgeExcel;
import com.markerhub.entity.SysDictValue;
import com.markerhub.service.HealthKnowledgeService;
import com.markerhub.service.SysDictValueService;
import com.markerhub.service.impl.HealthKnowledgeServiceImpl;
import com.markerhub.service.impl.SysDictValueServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jsx on 2023/1/27
 **/
@Repository
public class HealthKnowledgeListener extends AnalysisEventListener<HealthKnowledgeExcel> {

    SysDictValueService sysDictValueService;

    List<HealthKnowledgeExcel> list  = new ArrayList<>();

    HealthKnowledgeService healthKnowledgeService;

    public HealthKnowledgeListener(SysDictValueService sysDictValueService, HealthKnowledgeService healthKnowledgeService) {
        this.sysDictValueService = sysDictValueService;
        this.healthKnowledgeService = healthKnowledgeService;
    }

    @Override
    public void invoke(HealthKnowledgeExcel healthKnowledgeExcel, AnalysisContext analysisContext) {
        list.add(healthKnowledgeExcel);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        saveData();
    }

    private void saveData() {
        //查询所有的营养的类型
        List<SysDictValue> knowledgeType = sysDictValueService.getList("knowledgeType");
        List<HealthKnowledge> healthKnowledgeList = new ArrayList<>();
        healthKnowledgeList = list.stream().map(excel ->{
            HealthKnowledge healthKnowledge = new HealthKnowledge();
            healthKnowledge.setId(IdWorker.getIdStr());
            healthKnowledge.setFood(excel.getFood());
            healthKnowledge.setResult(excel.getResult());
            healthKnowledge.setDescription(excel.getDescription());
            for (SysDictValue value : knowledgeType) {
                if(value.getValue().equals(excel.getType())){
                    healthKnowledge.setType(value.getId());
                    break;
                }
            }
            return  healthKnowledge;
        }).collect(Collectors.toList());
        if(healthKnowledgeList.size() > 0){
            healthKnowledgeService.saveAllKnowledge(healthKnowledgeList);
        }

    }

}
